import React, { use, useEffect, useState } from 'react';
import { Table, Button, Modal, Select, message } from 'antd';
import axios from 'axios';

const UserList = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [allRoles, setAllRoles] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selectedRoles, setSelectedRoles] = useState([]);
  const [currentUser, setCurrentUser] = useState(null);

  useEffect(() => {
    fetchUsers();
    fetchRoles();
  }, []);

  const fetchUsers = async () => {
    try {
      setLoading(true);
      const response = await axios.get('http://localhost:3000/getUsers');
      setUsers(response.data.data);
      console.log(response.data.data);
    } catch (error) {
      console.error('获取用户列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 获取所有的角色
  const fetchRoles = async () => {
    try {
      setLoading(true);
      const response = await axios.get('http://localhost:3000/getRoles');
      setAllRoles(response.data.data);
      console.log(response.data.data);
    } catch (error) {
      console.error('获取所有角色失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 打开模态框并设置当前用户和角色
  const showRoleModal = (record) => {
    setCurrentUser(record);
    // 将字符串转换为数组（如果是字符串的话）
    const userRoles = typeof record.roles === 'string' 
      ? record.roles.split(',').filter(role => role) 
      : record.roles || [];
      console.log(userRoles);
      
    setSelectedRoles(userRoles);
    setIsModalVisible(true);
  };

  // 处理角色变更
  const handleRoleChange = (values) => {
    console.log(values);
    setSelectedRoles(values);
  };

  // 处理确认按钮
  const handleOk = async () => {
    try {
      setLoading(true);
      
      await axios.post('http://localhost:3000/saveRoles', {
        _id: currentUser._id,
        roles: selectedRoles.join(',')
      });
      message.success('角色更新成功');
      fetchUsers(); // 重新获取用户列表
      setIsModalVisible(false);
    } catch (error) {
      console.error('更新角色失败:', error);
      message.error('更新角色失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理取消按钮
  const handleCancel = () => {
    setIsModalVisible(false);
    setSelectedRoles([]);
    setCurrentUser(null);
  };

  const columns = [
    {
      title: '姓名',
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '角色',
      dataIndex: 'roles',
      key: 'roles'
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Button 
          type="primary" 
          size="small" 
          onClick={() => showRoleModal(record)}
        >
          分配角色
        </Button>
      ),
    },
  ];

  return (
    <div style={{ padding: '20px' }}>
      <h1>用户列表</h1>
      <Table 
        columns={columns}
        dataSource={users}
        rowKey="_id"
        loading={loading}
      />
      <Modal
        title="修改角色"
        open={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        confirmLoading={loading}
      >
        <Select
          mode="multiple"
          style={{ width: '100%' }}
          placeholder="请选择角色"
          value={selectedRoles}
          onChange={handleRoleChange}
          options={allRoles.map(role => ({
            label: role.title,
            value: role.id
          }))}
        />
      </Modal>
    </div>
  );
};

export default UserList; 